Skip to main content

1592. Rearrange Spaces Between Words

Question

You are given a string text of words that are placed among some number of spaces. Each word consists of one or more lowercase English letters and are separated by at least one space. It's guaranteed that text contains at least one word.

Rearrange the spaces so that there is an equal number of spaces between every pair of adjacent words and that number is maximized. If you cannot redistribute all the spaces equally, place the extra spaces at the end, meaning the returned string should be the same length as text.

Return the string after rearranging the spaces.

Example 1:

Input: text = "  this   is  a sentence "
Output: "this is a sentence"
Explanation: There are a total of 9 spaces and 4 words. We can evenly divide the 9 spaces between the words: 9 / (4-1) = 3 spaces.

Example 2:

Input: text = " practice   makes   perfect"
Output: "practice makes perfect "
Explanation: There are a total of 7 spaces and 3 words. 7 / (3-1) = 3 spaces plus 1 extra space. We place this extra space at the end of the string.

Constraints:

- 1 <= text.length <= 100
- text consists of lowercase English letters and ' '.
- text contains at least one word.

Approach

  1. First count the total number of spaces and at the same time retrieve the individual words.
  2. If there is no space at all, directly return the input text.
  3. If there are multiple words, calculate the spaces needed in between each word by <number of spaces> / number of words.
  4. If there is a remainder, keep track of <number of spaces> % number of words, these are the spaces we need to append to the end.
  5. If there is only one word, spaces need to be appended behind as well, we can directly set the number of spaces as the remainder.
  6. Construct the string and add the spaces in between accordingly.
  7. Append the remaining number of spaces if any.

Solution

class Solution {
public:
string reorderSpaces(string text) {
int spaceCount = 0;
string word = "";
vector<string> words;

for(int i = 0; i < text.size(); i++){
if(text[i] == ' '){
spaceCount ++;
if(!word.empty()){
words.push_back(word);
word.clear();
continue;
}
}
else word += text[i];

if(i == text.size() -1 && !word.empty()) words.push_back(word);
}

int each, rem;
if(spaceCount == 0) return text;
if(words.size()- 1 != 0){
each = spaceCount/(words.size()-1);
rem = spaceCount%(words.size()-1);
}else{
rem = spaceCount;
}

string out;
for(int i = 0; i < words.size(); i++){
out += words[i];
if (each != 0 && i != words.size() - 1){
for(int j = 1; j <= each; j++){
out += " ";
}
}
}

if(rem != 0){
while(rem > 0){
out += " ";
rem--;
}
}
return out;
}
};